package indi.zhifa.expshare.class001.mongodb.log;

import com.mongodb.event.CommandFailedEvent;
import com.mongodb.event.CommandListener;
import com.mongodb.event.CommandStartedEvent;
import com.mongodb.event.CommandSucceededEvent;
import org.bson.json.JsonMode;
import org.bson.json.JsonWriterSettings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

public class Slf4jCommandListener implements CommandListener {

    private static final Logger LOGGER = LoggerFactory.getLogger("MongoCommand");
    JsonWriterSettings jsonWriterSettings = JsonWriterSettings.builder()
            .outputMode(JsonMode.RELAXED)
            .build();

    @Override
    public void commandStarted(CommandStartedEvent event) {
        LOGGER.info("MongoCommand STARTED: {} - {}", event.getCommandName(), event.getCommand().toJson(jsonWriterSettings));
    }

    @Override
    public void commandSucceeded(CommandSucceededEvent event) {
        LOGGER.info("MongoCommand SUCCEEDED: {} - duration={}ms", event.getCommandName(), event.getElapsedTime(TimeUnit.MILLISECONDS));
    }

    @Override
    public void commandFailed(CommandFailedEvent event) {
        LOGGER.error("MongoCommand FAILED: {} - {}", event.getCommandName(), event.getThrowable().getMessage());
    }
}
